package com.learning.javaweb_servlet_jdbc;

import java.sql.*;

public class JDBC_Teacher_Batch_Processing {
    //设置基础数据，链接数据库
    static final String URL = "jdbc:mysql://localhost:3306/jdbc_demo?useSSL=false&serverTimezone=GMT&characterEncoding=UTF-8";
    static final String USER = "root";
    static final String PASSWORD = "WQ9ABCAT";

    // 批量插入数据
    static final String SQL = "INSERT INTO teacher(id,name,course,birthday) VALUES (?,?,?,?)";
    public static void main(String[] args) {


        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);) {
            conn.setAutoCommit(false);
            try (PreparedStatement ps = conn.prepareStatement(SQL);) {
                // 设置参数
                for (int i = 10; i < 510; i++) {
                    ps.setInt(1, i);
                    ps.setString(2, "name" + i);
                    ps.setString(3, "course" + i);

                    Date sqlDate = Date.valueOf("2020-07-01");
                    ps.setDate(4, sqlDate);

                    // 添加到批处理
                    ps.addBatch();
                    if (i % 100 == 0) { // 每100条记录执行一次批处理
                        ps.executeBatch();
                        ps.clearBatch();
                    }
                }
                ps.executeBatch();
                conn.commit();
                System.out.println("完成批量插入数据");
            } catch (SQLException e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}